Socket

  • Each socket = one endpoint of a single connection.

Socket IDs (File Descriptors) (fd)

  • File descriptor :

    • The term file descriptor comes from Unix and Unix-like operating systems, and itโ€™s deeply rooted in how these systems abstract I/O.

    • In Unix philosophy, "everything is a file".

      • Disk files

      • Pipes

      • Devices

      • Sockets

      • Terminals

      • Etc.

    • So:

      • When you open a file โ†’ you get a file descriptor.

      • When you open a socket โ†’ you also get a file descriptor.

    • Theyโ€™re both handled through the same I/O API: read() , write() , close() , etc.

    • This abstraction is why sockets use file descriptors โ€” theyโ€™re just "special files" from the OSโ€™s point of view.

  • Usage :

    • The socket ID is used by your program to interact with the OS-managed socket.

    • The OS routes TCP packets based on the socket's internal connection tuple, not your program directly.

      • Local Socket A: 127.0.0.1:6060

      • Local Socket B: 127.0.0.1:50543 -> 127.0.0.1:6061

    • The OS  stores and manages the mapping between:

      • Socket ID

      • The internal state of that connection

      • File/socket types, flags, permissions, etc.

    • You can think of the socket ID  as an index or key into a kernel-managed table of open resources, much like a hashmap, though it's typically implemented as a simple indexed array inside the OS.

  • You can safely have one listening socket on 6060  and one connected socket to 6061  in the same program.